package com.sevlet.setting;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JsonUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用文件 上传组件接收文件
        FileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);


        JsonUtil jsonUtil = new JsonUtil();
        try {
            //解析req对象，将表单数据解析为FileItem对象，多个表单数据用List表示
            List<FileItem> fileItemList  =    servletFileUpload.parseRequest(req);//

            for(FileItem fileItem :fileItemList){
                if ( fileItem.isFormField()) {//判断传递过来的参数是普通的表单字段，还是一个文件上传的字段
                    System.out.println("普通表单字段的名称为:"+fileItem.getFieldName() +"对应的值为:"+fileItem.getString());
                }else{
                    //文件上传的字段,用IO流读取文件内容
                    //应该把文件保存到项目运行的tomcat对应目录下

                    String realPath =   req.getServletContext().getRealPath("/img");
                    System.out.println("得到项目所运行的tocmat的真实(电脑)路径:"+realPath);
                    //E:\SpringColud\code\MyWeb2\target\MyWeb2\img\aa.png

                    File paretDir = new File(realPath);
                    if (!paretDir.exists())  {
                        paretDir.mkdirs();
                    }

                    String uploadFileName = fileItem.getName();
                    System.out.println("上传的文件名为:"+uploadFileName);



                    FileOutputStream fileOutputStream = new FileOutputStream(new File(paretDir,uploadFileName));


                    InputStream inputStream =  fileItem.getInputStream();
                    byte[] buf = new byte[1024];
                    int len =0;
                    while( (len = inputStream.read(buf))!=-1){
                        /// System.out.println("收到的文件内容为:"+new String(buf,0,len));
                        fileOutputStream.write(buf,0,len);
                    }
                    inputStream.close();
                    fileOutputStream.close();
                    System.out.println("文件上传成功");


                    jsonUtil.setCode(0);
                    jsonUtil.setMsg("成功");
                    //http://IP:8089/MyWeb2/img/文件名

                    Integer port =  req.getLocalPort();//得到端口号
                    String ip  =   req.getLocalAddr();;//得到ip
                    String contextPath1 =   req.getContextPath();//得到上下文路径


                    String imgPath = "http://"+ip+":"+port+contextPath1+"/img/"+uploadFileName;

                    jsonUtil.setData(imgPath);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("文件上传失败:"+e.getMessage());
        }


        resp.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter = resp.getWriter();

        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();


        printWriter.print(gson.toJson(jsonUtil));
    }
}

